﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using DAO;
using Domain;

public partial class UsrManageSuscripciones : System.Web.UI.Page
{
    private string accion {
        get {
            if (Request.QueryString["a"] != null &&
               Request.QueryString["a"].ToString() == "e")
            {
                return "e"; 
            }
            else
            {
                return "m";
            }
        }     
   }

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            if (accion == "m")
            {
                rbl_accion.SelectedIndex = 0;
                pnl_MisSuscripciones.Visible = true;
            }
            else
            {
                rbl_accion.SelectedIndex = 1;
                pnl_MisSuscripciones.Visible = false;
            }
            pnl_Explorar.Visible = !pnl_MisSuscripciones.Visible;

            bindearMisSuscripciones();


            string empresas = "";

            // traigo todas las empresas
            List<Empresa> lst = EmpresaDAO.Traer(null, null, null);
            lst.ForEach(delegate(Empresa emp)
            {
                if (!emp.Long.HasValue)
                    return;

                empresas += "markers_info.push({ title : '"+ emp.RazonSocial +
                            "', info : '" + "<a href=\"" + ResolveClientUrl(Utils.SecureRedirect("~/UsrEmpData.aspx?id=" + emp.UserName)) + "\" >"  + 
                            (!emp.Logo.HasValue ? string.Empty : "<img style=\"width:50px;float:left;\" src=\"ImageHandler.ashx?id=" + emp.Logo.Value + "\" />") +
                            emp.RazonSocial + "</a>" +
                             "', localization : new google.maps.LatLng(" + emp.Lat.Value.ToString().Replace(',', '.') + ", " + emp.Long.Value.ToString().Replace(',', '.')  + ") });";

            });

            ScriptManager.RegisterClientScriptBlock(Page, typeof(Page), "markers_info_add", empresas, true);
        }
    }



    protected void rbl_accion_SelectedIndexChanged(object sender, EventArgs e)
    {
        
        if (rbl_accion.SelectedItem.Value == "0")
            Response.Redirect(Utils.SecureRedirect("~/UsrManageSuscripciones.aspx?a=m"));    
        else
            Response.Redirect(Utils.SecureRedirect("~/UsrManageSuscripciones.aspx?a=e"));
        
    }

    private void bindearMisSuscripciones()
    {
        Usuario usr = (Usuario)Utils.operadorLogueado;
        if (usr.Asociaciones == null)
            return;

        List<Object> lst = new List<object>();
        usr.AsociacionesActivas.ForEach(delegate(Asociacion a) {
            if (a.IdEmpresa.HasValue)
            {
                lst.Add(EmpresaDAO.Traer(a.IdEmpresa.Value));
            }
            else
            {
                lst.AddRange(PublicacionDAO.Traer(a.IdPublicidad.Value, null,null).ToArray());
            }
        
        });


        var data = from l in lst
                   select new
                   {
                       idempresa = l is Empresa ? (long?) ((Empresa) l).UserName : null,
                       idpublicacion = l is Publicacion ? (long?) ((Publicacion) l).Id : null,
                       Logo = ResolveClientUrl(Utils.imageHandlerPath(l is Empresa ? ((Empresa) l).Logo : ((Publicacion) l).Logo,l is Empresa)),
                       Descripcion = l is Empresa ? ((Empresa) l).RazonSocial : ((Publicacion) l).Descripcion,
                       link = (l is Empresa ?
                                        "<a icon='search' href='" + ResolveClientUrl(Utils.SecureRedirect("~/UsrEmpData.aspx?id=" + ((Empresa)l).UserName)) + "' >Ver</a>" :
                                        "<a icon='search' href='" + ResolveClientUrl(Utils.SecureRedirect("~/UsrPublicacionData.aspx?id=" + ((Publicacion)l).Id)) + "' >Ver</a>")
                   };
        dg_MisSuscripciones.DataSource = data;
        dg_MisSuscripciones.DataBind();

        if (data.Count() > 0)
        {
            dg_MisSuscripciones.Visible = true;
            lbl_nosuscripciones.Visible = false;
        }
        else
        {
            dg_MisSuscripciones.Visible = false;
            lbl_nosuscripciones.Visible = true;
        }

    }
    protected void btn_buscar_Click(object sender, EventArgs e)
    {
        string[] tokens = txt_busqueda.Text.Split(':');
        string razon = null, rubro = null, desc = null;
        long? nro = null;

        if (tokens.Count() > 0)
        {
            if (tokens.ToList().IndexOf("razon") >= 0)
                razon = tokens[tokens.ToList().IndexOf("razon") + 1];

            if (tokens.ToList().IndexOf("rubro") >= 0)
                rubro = tokens[tokens.ToList().IndexOf("rubro") + 1];

            if (tokens.ToList().IndexOf("desc") >= 0)
                desc = tokens[tokens.ToList().IndexOf("desc") + 1];

            long l;
            if (tokens.ToList().IndexOf("nro") >= 0)
                if (long.TryParse(tokens[tokens.ToList().IndexOf("nro") + 1], out l) && l > 0)
                    nro = l;

            if (razon == null && rubro == null && desc == null && !nro.HasValue)
            {
                razon = txt_busqueda.Text;
                desc = txt_busqueda.Text;
            }

        }
        else
        {
            razon = txt_busqueda.Text;
            desc = txt_busqueda.Text;
        }

        List<Object> lst = new List<object>();
        if (!(razon == null && rubro == null))
            lst.AddRange(EmpresaDAO.Traer(null, razon,rubro).ToArray());
        if (!(desc == null && !nro.HasValue))
            lst.AddRange(PublicacionDAO.Traer(nro, desc, Publicacion.enum_Publicacion_Estado.Publicada).ToArray());

        var data = from l in lst
                   select new
                   {
                       idempresa = l is Empresa ? (long?)((Empresa)l).UserName : null,
                       idpublicacion = l is Publicacion ? (long?)((Publicacion)l).Id : null,
                       Logo = ResolveClientUrl(Utils.imageHandlerPath(l is Empresa ? ((Empresa)l).Logo : ((Publicacion)l).Logo, l is Empresa)),
                       Descripcion = l is Empresa ? ((Empresa)l).RazonSocial : ((Publicacion)l).Descripcion,
                       link = (l is Empresa ?
                                        "<a icon='search' href='" + ResolveClientUrl(Utils.SecureRedirect("~/UsrEmpData.aspx?id=" + ((Empresa)l).UserName)) + "' >Ver</a>" :
                                        "<a icon='search' href='" + ResolveClientUrl(Utils.SecureRedirect("~/UsrPublicacionData.aspx?id=" + ((Publicacion)l).Id)) + "' >Ver</a>")
                   };
        dg_Exploracion.DataSource = data;
        dg_Exploracion.DataBind();

        if (data.Count() > 0)
        {
            dg_Exploracion.Visible = true;
            lbl_nobusqueda.Visible = false;
        }
        else
        {
            dg_Exploracion.Visible = false;
            lbl_nobusqueda.Visible = true;
        }
    }
}
